package com.cn.zhongxj.jetpack.db.repository

import com.cn.zhongxj.jetpack.db.AppSqliteDataBase
import com.cn.zhongxj.jetpack.db.entity.SearchHistory
import com.cn.zhongxj.jetpack.db.entity.TestEntity

class SearchHistoryRepository(private val db: AppSqliteDataBase) {
    /**
     * 获取搜索列表
     */
    fun getSearchHistoryList(): MutableList<SearchHistory> {
        return db.searchHistoryDao().getAllHistory()
    }

    /**
     * 新增搜索历史记录
     */
    suspend fun insertHistory(searchHistory: SearchHistory) {
        val oldHistory = db
            .searchHistoryDao()
            .findSearchHistoryById(searchHistory.id)

        if (oldHistory != null) {
            db.searchHistoryDao().update(searchHistory)
        } else {
            db.searchHistoryDao().insertHistory(searchHistory)
        }
    }

    /**
     * 通过ID删除历史记录
     */
    suspend fun deleteById(id: Long) {
        val searchHistory = db.searchHistoryDao().findSearchHistoryById(id)
        if (searchHistory != null) {
            // 将删除的标志更新成1，表示已经删除
            searchHistory.isDelete = "1"
            db.searchHistoryDao().update(searchHistory)
        }
    }

    /**
     * 更新历史记录
     */
    suspend fun updateHistory(searchHistory: SearchHistory) {
        db.searchHistoryDao().update(searchHistory)
    }

    /**
     * 清除历史记录
     */
    suspend fun clearAllHistory() {
        db.searchHistoryDao().clearAll()
    }

    fun getTestList():MutableList<TestEntity>{
        return db.testEntityDao().getAll()
    }

    suspend fun insertTest(testEntity: TestEntity){
        db.testEntityDao().insertTest(testEntity)
    }
}